package top.huhuiyu.spirngboot2.total.ds;

public class MyStack<T> {
    // 栈只关心头节点
    private Node<T> head;
    private int count = 0;

    public boolean isEmpty() {
        return head == null;
    }

    public int size() {
        return count;
    }

    public void push(T data) {
        Node<T> node = new Node<T>();
        node.setData(data);
        // 没有数据的情况
//        if (head == null) {
//            head = node;
//        }else{
//            node.setNext(head);
//            head=node;
//        }
        // 1 head==null node.setNext(null) head=1
        // 2 head==1 node.setNext(1) head=2
        // 2 head==2 next==1 head=1
        // 1 head==1 next==null head=null

        node.setNext(head);
        head = node;
        count++;
    }

    public T pop() throws IllegalAccessException {
        if (isEmpty()) {
            throw new IllegalAccessException("堆栈是空的");
        }
        T data = head.getData();
        head = head.getNext();
        count--;
        return data;
    }

    public T peek() {
        return head == null ? null : head.getData();
    }

}
